<template>
  <div class="main-container">
    <el-table :data="tableData" style="width: 100%;height: 100%" border stripe>
      <el-table-column prop="name" label="用户名" width="150" />
      <el-table-column prop="sex" label="性别" width="120">
        <template #default="scope">
          {{ scope.row.sex == 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="economizeName" label="所在省份" width="120" />
      <el-table-column prop="marketName" label="所在市" width="150" />
      <el-table-column prop="cityName" label="所在县" width="150" />
      <el-table-column prop="address" label="地址详情" width="150" />
      <el-table-column prop="createTime" label="创建时间" width="120">
        <template #default="scope">
          {{ scope.row.createTime.split('T')[0] }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="180">
        <template #default="scope">
          <el-button link type="primary" @click="dialogFormVisible = true; FanTian(scope.row)">修改</el-button>
          <el-button link type="danger" @click="deleteData(scope.row.mainId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogFormVisible" title="修改" width="500" class="dialog-custom">
      <el-form>
        <el-form-item label="用户名:" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label='性别:' prop='sex'>
          <el-radio-group v-model="ruleForm.sex">
            <el-radio :value="true" size="small">男</el-radio>
            <el-radio :value="false" size="small">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所在地址:">
          <div id="app">
            <el-cascader size="large" :options="pcaTextArr" v-model="selectedOptions" @change="getAddress()"
              class="cascader-custom">
            </el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="详细信息:" prop="address">
          <el-input v-model="ruleForm.address" type="textarea" />
        </el-form-item>
        <el-form-item>
          <template #default="scope">
            <el-button link type="primary" @click="Update()">
              修改
            </el-button>
            <el-button link type="primary">取消</el-button>
          </template>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize" :page-sizes="[1, 2, 3, 4]"
      layout="total, sizes, prev, pager, next, jumper" :total="page.totalCount" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" class="pagination-custom" />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCounterStore } from "@/stores/counter"
const store = useCounterStore();
import { read, write } from "@/axios/axiosHelper"
import {
  provinceAndCityData,
  pcTextArr,
  regionData,
  pcaTextArr,
  codeToText,
} from "element-china-area-data";

const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const getAddress = () => {
  console.log(selectedOptions.value);
  ruleForm.economizeName = selectedOptions.value[0]
  ruleForm.marketName = selectedOptions.value[1]
  ruleForm.cityName = selectedOptions.value[2]
}
const selectedOptions = ref([]);
onMounted(() => {
  GetMain();
})

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  page.value.pageSize = val;
  GetMain();
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  page.value.pageIndex = val;
  GetMain();
}

const econeomizeList = ref([]);

const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

const tableData = ref([]);

const ruleForm = reactive({
  mainId: 1,
  name: "",
  sex: true,
  economizeId: 1,
  marketId: 1,
  cityId: 1,
  address: "",
  userId: 1,
  createTime: "",
  modifyId: 0,
  updateTime: "",
  isDelete: true,
  userName: "",
  password: "",
  userNickName: "",
  marketName: "",
  economizeName: "",
  cityName: ""
});

const Update = () => {
  write.put('/write/api/Main/UpdateMain', ruleForm).then(res => {
    if (res.data.code === 400) {
      ElMessage.success('修改成功')
      dialogFormVisible.value = false
      GetMain();
    } else {
      ElMessage.error('修改失败')
    }
  })
}

const FanTian = (row: any) => {
  ruleForm.address = row.address;
  ruleForm.cityId = row.cityId;
  ruleForm.economizeId = row.economizeId;
  ruleForm.mainId = row.mainId;
  ruleForm.marketId = row.marketId;
  ruleForm.name = row.name;
  ruleForm.sex = row.sex;
  ruleForm.userId = store.counterStore.userId;
  ruleForm.userName = store.counterStore.userName;
  ruleForm.userNickName = row.userNickName;
  ruleForm.password = row.password;
  ruleForm.createTime = row.createTime;
  ruleForm.modifyId = store.counterStore.userId;
  ruleForm.updateTime = row.updateTime;
  ruleForm.isDelete = row.isDelete;
  ruleForm.economizeName = row.economizeName;
  ruleForm.marketName = row.marketName;
  ruleForm.cityName = row.cityName;

  // 反填三级联动
  const province = pcaTextArr.find(item => item.label === row.economizeName);
  if (province) {
    const city = province.children.find(item => item.label === row.marketName);
    if (city) {
      const county = city.children.find(item => item.label === row.cityName);
      if (county) {
        selectedOptions.value = [row.economizeName, row.marketName, row.cityName];
      }
    }
  }
}

const page = ref({
  pageIndex: 1,
  pageSize: 5,
  totalCount: 0,
  totalPage: 0
})

const GetMain = () => {
  axios.get("/read/api/Main/Handle", {
    params: {
      pageIndex: page.value.pageIndex,
      pageSize: page.value.pageSize
    }
  }).then(res => {
    console.log(res.data)
    tableData.value = res.data.data
    page.value.totalCount = res.data.totalCount
    page.value.totalPage = res.data.totalPage
  })
}

const deleteData = (mainId: number) => {
  ElMessageBox.confirm('确定要删除这条数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    write.put('/write/api/Main/DelMain', { mainId })
      .then(() => {
        ElMessage.success('删除成功');
        // 重新获取数据
        GetMain();
      })
      .catch(() => {
        ElMessage.error('删除失败');
      });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};
</script>

<style scoped>
.main-container {
  padding: 20px;
  background-color: #f4f4f4;
  border-radius: 8px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}

.el-table {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.el-table:hover {
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.dialog-custom {
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

.cascader-custom {
  width: 100%;
}

.pagination-custom {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>